package bev.article;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;

import bev.ConnectionManager;
import bev.HelperUtility;

/**
 * Used to store and work with article data about a place in memory.
 */
public class PlaceArticle extends BaseArticle {
    // Place article data.
    String description, history, climate, attractions;

    // Text fields for editing
    JTextField txtDescription;
    JTextArea txtHistory;
    JTextArea txtClimate;
    JTextArea txtAttractions;

    /**
     * Instantiates a new <i>place</i> article.
     */
    public PlaceArticle() {
        super();

        // Default values.
        description = "";
        history = "";
        climate = "";
        attractions = "";
    }

    @Override
    public void loadArticle( int id ) {
        id_num = id;

        // Get the results set containing the place.
        try {
            ResultSet rs = ConnectionManager
                    .RunSQLQuery( String
                            .format(
                                    "SELECT id, name, description, created, updated, history, climate, attractions FROM places WHERE id = %d",
                                    id ) );

            if ( rs.next() ) {
                int place_id = rs.getInt( "id" );
                if ( place_id != id ) {
                    System.err.print( "ID from database did not match." );
                    return;
                }

                // Common data.
                name = HelperUtility.stringOrDefault( rs.getString( "name" ) );
                timeCreated = rs.getTimestamp( "created" );
                timeModified = rs.getTimestamp( "updated" );

                // Place data.
                description = HelperUtility.stringOrDefault( rs
                        .getString( "description" ) );
                history = HelperUtility.stringOrDefault( rs
                        .getString( "history" ) );
                climate = HelperUtility.stringOrDefault( rs
                        .getString( "climate" ) );
                attractions = HelperUtility.stringOrDefault( rs
                        .getString( "attractions" ) );

            }

            ConnectionManager.closeConnection();
        } catch ( SQLException ex ) {
            ex.printStackTrace();
        } catch ( ClassNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    @Override
    public void storeArticle() {
        try {
            // Get all the place article IDs from the database.
            ResultSet rs = ConnectionManager
                    .RunSQLQuery( "SELECT id FROM places" );

            // Check if this article's ID exists in database.
            boolean exists = false;
            while ( rs.next() ) {
                int person_id = rs.getInt( "id" );
                if ( person_id == id_num ) {
                    exists = true;
                    break;
                }
            }

            // Update article in database if it exists.
            if ( exists ) {
                String query = String
                        .format(
                                //                 name,      desc,      hist,      clim,      attr
                                "UPDATE places SET %s = '%s', %s = '%s', %s = '%s', %s = '%s', %s = '%s' WHERE id = %d",
                                "name", ConnectionManager.processEscapeChars( name ),
                                "description", ConnectionManager.processEscapeChars( description ),
                                "history", ConnectionManager.processEscapeChars( history ),
                                "climate", ConnectionManager.processEscapeChars( climate ),
                                "attractions", ConnectionManager.processEscapeChars( attractions ),
                                id_num );

                System.out.printf( "Insert query: '%s'\n", query );
                ConnectionManager.RunSQLUpdateQuery( query );
            }
            // Else insert as a new article.
            else {
                String query = String
                        .format(
                                "INSERT INTO places (name, description, created, history, climate, attractions) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
                                ConnectionManager.processEscapeChars( name ),
                                ConnectionManager.processEscapeChars( description ),
                                HelperUtility.formatDatabaseTimeStamp( timeCreated ),
                                ConnectionManager.processEscapeChars( history ),
                                ConnectionManager.processEscapeChars( climate ),
                                ConnectionManager.processEscapeChars( attractions ) );

                System.out.printf( "Insert query: '%s'\n", query );
                ConnectionManager.RunSQLUpdateQuery( query );
            }

            ConnectionManager.closeConnection();
        } catch ( SQLException ex ) {
            ex.printStackTrace();
        } catch ( ClassNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void addBodyText( JTextPane textPane ) {
        // Description.
        if ( description.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "Description" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, description );
            ArticleFormatter.addNewLine( textPane, 2 );
        }

        // History.
        if ( history.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "History" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, history );
            ArticleFormatter.addNewLine( textPane, 2 );
        }

        // Climate
        if ( climate.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "Climate" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, climate );
            ArticleFormatter.addNewLine( textPane, 2 );
        }

        // Attractions
        if ( attractions.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "Attractions" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, attractions );
            ArticleFormatter.addNewLine( textPane, 1 );
        }
    }

    @Override
    protected JPanel getBodyEditControls() {
        ArticleEditPanel panel = new ArticleEditPanel();

        // Description.
        txtDescription = new JTextField( description );

        // History.
        txtHistory = new JTextArea( history );
        txtHistory.setLineWrap( true );
        JScrollPane spHistory = new JScrollPane( txtHistory );
        spHistory
                .setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );

        // Climate.
        txtClimate = new JTextArea( climate );
        txtClimate.setLineWrap( true );
        JScrollPane spClimate = new JScrollPane( txtClimate );
        spClimate
                .setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );

        // Attractions.
        txtAttractions = new JTextArea( attractions );
        txtAttractions.setLineWrap( true );
        JScrollPane spAttractions = new JScrollPane( txtAttractions );
        spAttractions
                .setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );

        // Add the fields to the article edit view.

        panel.addComponent( "Description", txtDescription,
                ArticleEditPanel.getLargeFieldSize() );
        panel.commitComponents();

        panel.addComponent( "History", spHistory );
        panel.addComponent( "Climate", spClimate );
        panel.addComponent( "Attractions", spAttractions );
        panel.commitComponents();

        return panel;
    }

    @Override
    protected void saveCustomEditData() {
        description = HelperUtility.getTextNullCheck( txtDescription );
        history = HelperUtility.getTextNullCheck( txtHistory );
        climate = HelperUtility.getTextNullCheck( txtClimate );
        attractions = HelperUtility.getTextNullCheck( txtAttractions );
    }

    @Override
    protected boolean validateBodyEditFields() {
        // None for places

        return true;
    }
}
